package com.spotify.analysis.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spotify.analysis.dto.PageResult;
import com.spotify.analysis.dto.Result;
import com.spotify.analysis.dto.GenreDTO;
import com.spotify.analysis.dto.TrackRequestParam;
import com.spotify.analysis.entity.Track;
import com.spotify.analysis.service.TrackService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin(origins = "http://localhost:3000") // 仅此控制器生效
@RestController
@RequestMapping("/tracks")
@RequiredArgsConstructor
public class TrackController {
    private final TrackService trackService;

    /**
     * 获取歌曲列表
     */
    @GetMapping
    public Result<PageResult<GenreDTO>> getTracks(TrackRequestParam  param) {
        IPage<Track> trackPage = trackService.getTracks(param);
        
        // 转换Track实体为TrackDTO
        List<GenreDTO> trackDTOs = trackPage.getRecords().stream().map(Track::convertToDTO).collect(Collectors.toList());
        
        PageResult<GenreDTO> pageResult = new PageResult<>(trackPage.getTotal(), trackDTOs);
        return Result.success(pageResult);
    }

    /**
     * 获取指定歌曲的元数据
     */
    @GetMapping("/{id}")
    public Result<GenreDTO> getTrackById(@PathVariable String id) {
        Track track = trackService.getTrackById(id);
        
        // 转换Track实体为TrackDTO
        GenreDTO trackDTO = track.convertToDTO();
        return Result.success(trackDTO);
    }

    /**
     * 获取歌曲调式的分布
     */
    @GetMapping("/key")
    public Result<Map<String, Object>> getKeyDistribution(TrackRequestParam  param) {
        Map<String, Object> distribution = trackService.getKeyDistribution(param);
        return Result.success(distribution);
    }

    /**
     * 获取歌曲流派的分布
     */
    @GetMapping("/genre")
    public Result<Map<String, Object>> getGenreDistribution(TrackRequestParam  param) {
        Map<String, Object> distribution = trackService.getGenreDistribution(param);
        return Result.success(distribution);
    }

    /**
     * 获取歌曲的强度与活跃度的分布
     */
    @GetMapping("/energy")
    public Result<Map<String, Object>> getEnergyDistribution(TrackRequestParam  param) {
        Map<String, Object> distribution = trackService.getEnergyDistribution(param);
        return Result.success(distribution);
    }

    /**
     * 获取歌曲适合跳舞的程度的分布
     */
    @GetMapping("/danceability")
    public Result<Map<String, Object>> getDanceabilityDistribution(TrackRequestParam  param) {
        Map<String, Object> distribution = trackService.getDanceabilityDistribution(param);
        return Result.success(distribution);
    }
}